package pk1;
import java.io.IOException;
import shared.PMF;
import java.util.Date;
import shared.MyDateUtil;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.List;


public class ConfirmServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String nextJSP = "record.jsp";

	public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
		request.setCharacterEncoding("BIG5");
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String check1 = request.getParameter("check1");
		String check2 = request.getParameter("check2");
		String inviterd_ID = request.getParameter("inviterd_ID");
		String inviter_ID = request.getParameter("inviter_ID");
		String invite_activity= request.getParameter("invite_activity");
		String inviterd_con=request.getParameter("inviterd_con");
		String inviter_con=request.getParameter("inviter_con");
		String invite_message = request.getParameter("invite_message");
		Date invite_date = MyDateUtil.getTodayDate();
		try {	
			invite_date = MyDateUtil.parse(request.getParameter("invite_date"));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		try{
		if(check1!=null){
			Query query = pm.newQuery(Record.class);
			List<Record> result = (List<Record>) query.execute();
			if (!result.isEmpty()) {
				for (Record p : result) {
					if(String.valueOf(p.getInviterCon()).equals(inviter_con)){
						pm.deletePersistent(p);
					}
				}//for
			}//if
			String status = "Success";
			Record rec = new Record(inviterd_ID,inviter_ID,invite_activity,inviterd_con,inviter_con,invite_date,invite_message,status);
			pm.makePersistent(rec);
			response.sendRedirect(nextJSP);
		}
		if(check2!=null){
			Query query = pm.newQuery(Record.class);
			List<Record> results = (List<Record>) query.execute();
			if (!results.isEmpty()) {
				for (Record p : results) {
					if(String.valueOf(p.getInviterCon()).equals(inviter_con)){
						pm.deletePersistent(p);
					}
				}//for
			}//if
			String status = "Fail";
			Record rec = new Record(inviterd_ID,inviter_ID,invite_activity,inviterd_con,inviter_con,invite_date,invite_message,status);
			pm.makePersistent(rec);
			response.sendRedirect(nextJSP);
			
		}
		}finally{
			pm.close();
		}
    }
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException{
		doGet(request, response);
	}
}//AddProductServlet